// NavigationLayout.jsx
import React, { useState } from 'react';
import { Menu, message } from 'antd';
import axios from 'axios';
import { useLocation,useNavigate } from 'react-router-dom';

const NavigationLayout = ({ children }) => {
    const navigate = useNavigate();
    const loc = useLocation();                     // ② 改名，避免冲突
    const defaultKey = loc.pathname === '/' ? '0' : null;
    const [activeKey, setActiveKey] = useState(defaultKey);
    const menuItems = [
        { label: '信息录入', key: '0', url: '/' },
        { label: '结果核对', key: '1', url: '/checkResult' },
        { label: '任务一帮助', key: '2', url: '/wpshelper' },
        { label: '任务二帮助', key: '3', url: '/pythonhelper' },
        //{ label: '任务二结果核对', key: '4', url: '/checkPythonResult' },
    ];

    const handleMenuClick = async (item) => {
        const buttonValue = parseInt(item.key, 10);

        try {
            const response = await axios.get('/api/option/step', {
                params: { opkey: 'step' },
            });

            const { opvalue } = response.data;

            if (opvalue < buttonValue) {
                message.warning('该环节尚未开放，请稍后再进入。');
                return;
            }
            // 通过校验，才允许高亮并跳转
            setActiveKey(item.key); // ✅ 只在这里改变横条
            const target = menuItems.find((m) => m.key === item.key);
            if (target) navigate(target.url);
        } catch (error) {
            console.error('请求失败:', error);
            message.error('请求失败，请稍后重试。');
        }
    };

    return (
        <div>
            <Menu
                mode="horizontal"
                selectedKeys={[activeKey]}   // 控制横条
                items={menuItems}
                onClick={handleMenuClick}
                style={{ marginBottom: 24 }}
            />
            <div style={{ padding: '0 24px' }}>{children}</div>
        </div>
    );
};

export default NavigationLayout;